<template>
  <div class="chart-container w-full h-full min-h-0">
    <div 
      ref="chartRef" 
      class="w-full h-full" 
      :style="{ 
        height: typeof height === 'number' ? height + 'px' : height,
        minHeight: '200px'
      }"
    ></div>
  </div>
</template>

<script setup lang="ts">
import type { MarketInstrument, VolatilityData } from '~/types/market'
import { useTheme } from '~/composables/useTheme'
import * as echarts from 'echarts'

// Props
interface Props {
  instrument: MarketInstrument
  height?: string | number
}

const props = withDefaults(defineProps<Props>(), {
  height: '200px'
})

// 使用主题
const { isDark } = useTheme()

// 图表引用
const chartRef = ref<HTMLDivElement>()
const chartInstance = ref<echarts.ECharts>()

// 初始化图表
const initChart = () => {
  console.log('VolatilityChart: 开始初始化图表')
  console.log('容器元素:', chartRef.value)
  
  if (!chartRef.value) {
    console.error('VolatilityChart: 容器元素未找到')
    return
  }
  
  try {
    console.log('VolatilityChart: 创建ECharts实例')
    chartInstance.value = echarts.init(chartRef.value, null, {
      renderer: 'canvas',
      useDirtyRect: false
    })
    console.log('VolatilityChart: ECharts实例创建成功')
    
    // 确保图表撑满容器
    setTimeout(() => {
      if (chartInstance.value) {
        chartInstance.value.resize()
        updateChart()
      }
    }, 100)
  } catch (error) {
    console.error('VolatilityChart: 初始化失败', error)
  }
}

// 更新图表
const updateChart = () => {
  if (!chartInstance.value) return
  
  console.log('VolatilityChart: 更新图表数据')
  console.log('波动率数据:', props.instrument.volatilityData)
  console.log('持仓量数据:', props.instrument.openInterestData)
  
      const option = {
        backgroundColor: 'transparent',
        grid: {
          left: '3%',     // 最小化左侧边距
          right: '3%',    // 最小化右侧边距
          top: '8%',      // 减少顶部边距
          bottom: '8%',   // 减少底部边距
          containLabel: true
        },
        // 全局柱状图配置
        barMaxWidth: 8,
        barGap: '80%',
        barCategoryGap: '80%',
    xAxis: {
      type: 'category',
      name: '',
      nameTextStyle: {
        color: isDark.value ? '#94a3b8' : '#64748b',
        fontSize: 12
      },
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        color: isDark.value ? '#94a3b8' : '#64748b',
        fontSize: 10,
        interval: 0,
        rotate: 0
      },
      splitLine: {
        show: false
      },
      data: props.instrument.volatilityData.map(item => item.strike).sort((a, b) => a - b)
    },
    yAxis: [
      {
        type: 'value',
        name: '隐波(%)',
        nameTextStyle: {
          color: isDark.value ? '#94a3b8' : '#64748b',
          fontSize: 12
        },
        axisLine: {
          show: false  // 隐藏Y轴线
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          color: isDark.value ? '#94a3b8' : '#64748b',
          fontSize: 10,
          interval: 0  // 显示所有标签
        },
        splitLine: {
          show: false  // 隐藏Y轴网格线
        }
      },
      {
        type: 'value',
        name: '持仓量',
        nameTextStyle: {
          color: isDark.value ? '#94a3b8' : '#64748b',
          fontSize: 12
        },
        axisLine: {
          show: false  // 隐藏Y轴线
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          color: isDark.value ? '#94a3b8' : '#64748b',
          fontSize: 10,
          interval: 0  // 显示所有标签
        },
        splitLine: {
          show: false  // 隐藏Y轴网格线
        }
      }
    ],
    legend: {
      top: '8%',
      right: '2%',
      textStyle: {
        color: isDark.value ? '#cbd5e1' : '#475569',
        fontSize: 10
      },
      itemWidth: 8,
      itemHeight: 8,
      data: ['今日波动率', '昨日波动率', '持仓量']
    },
    tooltip: {
      show: true,
      trigger: 'axis',
      backgroundColor: isDark.value ? '#1e293b' : '#ffffff',
      borderColor: isDark.value ? '#334155' : '#e2e8f0',
      textStyle: {
        color: isDark.value ? '#cbd5e1' : '#475569'
      },
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      },
      formatter: function(params: any) {
        console.log('Tooltip formatter called with params:', params)
        if (Array.isArray(params) && params.length > 0) {
          let tooltipContent = ''
          
          // 添加价格标题
          const strikePrice = params[0].axisValue
          tooltipContent += `<div style="font-weight: 600; margin-bottom: 8px; color: ${isDark.value ? '#f1f5f9' : '#111827'}; font-size: 14px;">
            ${strikePrice}
          </div>`
          
          // 添加数据点信息
          params.forEach((param: any) => {
            if (param.seriesName === '今日波动率') {
              tooltipContent += `<div style="margin: 6px 0; display: flex; align-items: center;">
                <span style="display: inline-block; width: 8px; height: 8px; background: #8b5cf6; border-radius: 50%; margin-right: 8px;"></span>
                <span style="color: ${isDark.value ? '#cbd5e1' : '#374151'}; font-size: 13px;">今日波动率: <strong style="color: #8b5cf6; font-weight: 600;">${param.value.toFixed(2)}%</strong></span>
              </div>`
            } else if (param.seriesName === '昨日波动率') {
              const yesterdayColor = isDark.value ? '#64748b' : '#94a3b8'
              tooltipContent += `<div style="margin: 6px 0; display: flex; align-items: center;">
                <span style="display: inline-block; width: 8px; height: 8px; background: ${yesterdayColor}; border-radius: 50%; margin-right: 8px;"></span>
                <span style="color: ${isDark.value ? '#cbd5e1' : '#374151'}; font-size: 13px;">昨日波动率: <strong style="color: ${yesterdayColor}; font-weight: 600;">${param.value.toFixed(2)}%</strong></span>
              </div>`
            } else if (param.seriesName === '持仓量') {
              const color = param.dataIndex % 2 === 0 ? '#10b981' : '#ef4444'
              tooltipContent += `<div style="margin: 6px 0; display: flex; align-items: center;">
                <span style="display: inline-block; width: 8px; height: 8px; background: ${color}; border-radius: 2px; margin-right: 8px;"></span>
                <span style="color: ${isDark.value ? '#cbd5e1' : '#374151'}; font-size: 13px;">持仓量: <strong style="color: ${color}; font-weight: 600;">${param.value.toLocaleString()}</strong></span>
              </div>`
            }
          })
          
          console.log('Tooltip content:', tooltipContent)
          return tooltipContent
        }
        return ''
      }
    },
    series: [
      {
        name: '今日波动率',
        type: 'line',
        yAxisIndex: 0,
        data: props.instrument.volatilityData.map(item => item.impliedVol).sort((a, b) => a - b),
        lineStyle: {
          color: '#8b5cf6',
          width: 2
        },
        itemStyle: {
          color: '#8b5cf6'
        },
        symbol: 'circle',
        symbolSize: 4,
        smooth: true
      },
      {
        name: '昨日波动率',
        type: 'line',
        yAxisIndex: 0,
        data: props.instrument.volatilityData.map(item => item.impliedVol * 0.9).sort((a, b) => a - b),
        lineStyle: {
          color: isDark.value ? '#64748b' : '#94a3b8',
          width: 1,
          type: 'dashed'
        },
        itemStyle: {
          color: isDark.value ? '#64748b' : '#94a3b8'
        },
        symbol: 'rect',
        symbolSize: 3,
        smooth: true
      },
      {
        name: '持仓量',
        type: 'bar',
        yAxisIndex: 1,
        data: props.instrument.openInterestData.map((item, index) => ({
          value: item.openInterest,
          itemStyle: {
            color: index % 2 === 0 ? '#10b981' : '#ef4444'
          }
        })),
        itemStyle: {
          color: function(params: any) {
            return params.dataIndex % 2 === 0 ? '#10b981' : '#ef4444'
          }
        },
        barWidth: 8
      }
    ]
  }
  
  console.log('Setting ECharts option:', option)
  chartInstance.value.setOption(option)
  console.log('ECharts option set successfully')
}

// 监听主题变化
watch(isDark, () => {
  updateChart()
})

// 监听数据变化
watch(() => props.instrument, () => {
  updateChart()
}, { deep: true })

// 监听窗口大小变化
const handleResize = () => {
  if (chartInstance.value) {
    chartInstance.value.resize()
  }
}

// 使用ResizeObserver监听容器大小变化
const resizeObserver = ref<ResizeObserver | null>(null)

// 重置缩放
const resetZoom = () => {
  if (chartInstance.value) {
    chartInstance.value.dispatchAction({
      type: 'dataZoom',
      start: 0,
      end: 100
    })
  }
}

// 暴露重置缩放方法
defineExpose({
  resetZoom
})

// 组件挂载时初始化
onMounted(() => {
  nextTick(() => {
    initChart()
    
    // 设置ResizeObserver监听容器大小变化
    if (chartRef.value) {
      resizeObserver.value = new ResizeObserver(() => {
        if (chartInstance.value) {
          chartInstance.value.resize()
        }
      })
      resizeObserver.value.observe(chartRef.value)
    }
  })
  window.addEventListener('resize', handleResize)
})

// 组件卸载时清理
onUnmounted(() => {
  if (chartInstance.value) {
    chartInstance.value.dispose()
  }
  if (resizeObserver.value) {
    resizeObserver.value.disconnect()
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.chart-container {
  position: relative;
  width: 100%;
  height: 100%;
  min-height: 200px;
  display: flex;
  flex-direction: column;
}

.chart-container > div {
  flex: 1;
  min-height: 0;
}
</style>
